﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * This file is part of dnAnalytics.  dnAnalytics is licensed under the 
 * Microsoft Public License. See License.txt for a complete copy of the
 * license.
 */

using System;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The Dirichlet distribution is a distribution over probability vectors. It is parameterized by a vector of
    /// non-negative numbers.
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class Dirichlet
    {
        // The Dirichlet distribution parameters.
        private readonly double[] mAlpha;

        /// <summary>
        /// Constructs a new Dirichlet distribution.
        /// </summary>
        /// <param name="alpha">An array with the Dirichlet parameters.</param>
        public Dirichlet(double[] alpha)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(alpha);
            }

            mAlpha = alpha;
        }

        /// <summary>
        /// Constructs a new symmetric Dirichlet distribution.
        /// </summary>
        /// <param name="alpha">The value of each parameter of the Dirichlet distribution.</param>
        /// <param name="k">The dimension of the Dirichlet distribution.</param>
        public Dirichlet(double alpha, int k)
        {
            if (Control.CheckDistributionParameters)
            {
                if (alpha < 0.0)
                {
                    throw new ArgumentOutOfRangeException("alpha", "Alpha entries should be positive.");
                }

                if (k <= 0)
                {
                    throw new ArgumentOutOfRangeException("k", "The dimension of the Dirichlet distribution should be positive.");
                }
            }

            mAlpha = new double[k];
            for (int i = 0; i < k; i++)
            {
                mAlpha[i] = alpha;
            }
        }

        /// <summary>
        /// Gets the mean.
        /// </summary>
        /// <value>The mean.</value>
        public double[] Mean
        {
            get { return mAlpha; }
        }

        /// <summary>
        /// Gets the variance.
        /// </summary>
        /// <value>The variance.</value>
        public double[] Variance
        {
            get
            {
                double s = AlphaSum();
                double[] v = new double[mAlpha.Length];
                for (int i = 0; i < mAlpha.Length; i++)
                {
                    v[i] = mAlpha[i]*(s - mAlpha[i])/(s*s*(s + 1.0));
                }
                return v;
            }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        /// <summary>
        /// Computes the sum of all alpha parameters.
        /// </summary>
        private double AlphaSum()
        {
            double s = 0.0;
            for (int i = 0; i < mAlpha.Length; i++)
            {
                s += mAlpha[i];
            }
            return s;
        }

        /// <summary>
        /// Check the parameters of the distribution.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">If any of the components in the Dirichlet parameter vector are negative.</exception>
        public static void CheckParameters(double[] alpha)
        {
            for (int i = 0; i < alpha.Length; i++)
            {
                if (alpha[i] < 0.0)
                {
                    throw new ArgumentOutOfRangeException("alpha", "Alpha entries should be positive.");
                }
            }
        }

        /// <summary>
        /// Samples a Dirichlet distributed random vector.
        /// </summary>
        public double[] Sample()
        {
            return Sample(RandomNumberGenerator, mAlpha);
        }

        /// <summary>
        /// Samples a Dirichlet distributed random vector.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="alpha">The Dirichlet distribution parameter.</param>
        public static double[] Sample(System.Random rnd, double[] alpha)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(alpha);
            }

            int n = alpha.Length;
            double[] gv = new double[n];
            double sum = 0.0;
            for (int i = 0; i < n; i++)
            {
                gv[i] = Gamma.Sample(rnd, alpha[i], 1.0);
                sum += gv[i];
            }

            for (int i = 0; i < n; i++)
            {
                gv[i] /= sum;
            }

            return gv;
        }
    }
}